import request from '@/utils/request'
import axios from 'axios'

/**
 * 用户登录
 * @param {Object} data - 登录数据，包含用户名/手机号和密码
 * @returns {Promise} - 返回登录结果，包含token等信息
 */
export const login = (data) => {
  return request({
    url: '/userService/userController/login',
    method: 'post',
    data
  })
}

/**
 * 用户注册
 * @param {Object} data - 注册数据，包含用户名、密码、手机号等信息
 * @returns {Promise} - 返回注册结果
 */
export const register = (data) => {
  return request({
    url: '/userService/userController/register',
    method: 'post',
    data
  })
}

/**
 * 发送注册短信验证码
 * @param {string} mobile - 手机号码
 * @returns {Promise} - 返回发送结果
 */
export const sendSmsCode = (mobile) => {
  return request({
    url: '/userService/userController/sendRegisterMessageCode',
    method: 'get',
    params: { mobile }
  })
}

/**
 * 校验注册短信验证码
 * @param {string} mobile - 手机号码
 * @param {string} userCode - 用户输入的验证码
 * @returns {Promise} - 返回验证结果
 */
export const checkSmsCode = (mobile, userCode) => {
  return request({
    url: '/userService/userController/checkRegisterMessageCode',
    method: 'get',
    params: { 
      mobile,
      userCode
    }
  })
}

/**
 * 发送登录短信验证码
 * @param {string} mobile - 手机号码
 * @returns {Promise} - 返回发送结果
 */
export const sendLoginSmsCode = (mobile) => {
  return request({
    url: '/userService/userController/sendLoginMessageCode',
    method: 'get',
    params: { mobile }
  })
}

/**
 * 校验登录短信验证码
 * @param {string} mobile - 手机号码
 * @param {string} userCode - 用户输入的验证码
 * @returns {Promise} - 返回验证结果
 */
export const checkLoginSmsCode = (mobile, userCode) => {
  return request({
    url: '/userService/userController/checkLoginMessageCode',
    method: 'get',
    params: { 
      mobile,
      userCode
    }
  })
}

/**
 * 发送重置密码短信验证码
 * @param {string} mobile - 手机号码
 * @returns {Promise} - 返回发送结果
 */
export const sendResetPasswordSmsCode = (mobile) => {
  return request({
    url: '/userService/userController/sendResetMessageCode',
    method: 'get',
    params: { mobile }
  })
}

/**
 * 校验重置密码短信验证码
 * @param {string} mobile - 手机号码
 * @param {string} userCode - 用户输入的验证码
 * @returns {Promise} - 返回验证结果
 */
export const checkResetPasswordSmsCode = (mobile, userCode) => {
  return request({
    url: '/userService/userController/checkResetMessageCode',
    method: 'get',
    params: { 
      mobile,
      userCode
    }
  })
}

/**
 * 重置密码
 * @param {Object} data - 重置密码数据，包含用户名、手机号和新密码
 * @returns {Promise} - 返回重置结果
 */
export const resetPassword = (data) => {
  return request({
    url: '/userService/userController/resetPassword',
    method: 'post',
    data
  })
}

/**
 * 发送重置手机号短信验证码
 * @param {string} mobile - 手机号码
 * @returns {Promise} - 返回发送结果
 */
export const sendResetPhoneSmsCode = (mobile) => {
  return request({
    url: '/userService/userController/sendResetPhoneCode',
    method: 'get',
    params: { mobile }
  })
}

/**
 * 校验重置手机号短信验证码
 * @param {string} mobile - 手机号码
 * @param {string} userCode - 用户输入的验证码
 * @returns {Promise} - 返回验证结果
 */
export const checkResetPhoneSmsCode = (mobile, userCode) => {
  return request({
    url: '/userService/userController/checkResetPhoneCode',
    method: 'get',
    params: { 
      mobile,
      userCode
    }
  })
}

/**
 * 获取用户名
 * @returns {Promise} - 返回用户名
 */
export function getUserName() {
  return request({
    url: '/userService/userController/getUserName',
    method: 'get',
    headers: {
      Authorization: sessionStorage.getItem('token') || localStorage.getItem('token')
    }
  })
}

/**
 * 获取用户详细信息
 * @returns {Promise} - 返回用户详细信息，包含个人资料等
 */
export function getUserDetailsInfo() {
  return request({
    url: '/userService/userController/getUserDetailsInfo',
    method: 'get',
    headers: {
      Authorization: sessionStorage.getItem('token') || localStorage.getItem('token')
    }
  })
}

/**
 * 更新用户信息
 * @param {Object} data - 更新的用户信息数据
 * @returns {Promise} - 返回更新结果
 */
export function updateUserInfo(data) {
  return request({
    url: '/userService/userController/updateUserInfo',
    method: 'post',
    data,
    headers: {
      Authorization: sessionStorage.getItem('token') || localStorage.getItem('token')
    }
  })
}

/**
 * 修改用户手机号
 * @param {Object} data - 包含新手机号和验证码的数据
 * @returns {Promise} - 返回修改结果
 */
export function updateUserPhone(data) {
  return request({
    url: '/userService/userController/updateUserPhone',
    method: 'post',
    data,
    headers: {
      Authorization: sessionStorage.getItem('token') || localStorage.getItem('token')
    }
  })
}

/**
 * 上传用户头像
 * @param {File} file - 头像文件对象
 * @returns {Promise} - 返回上传结果，包含头像URL
 */
export function uploadAvatar(file) {
  const formData = new FormData();
  formData.append('file', file);
  
  return request({
    url: '/userService/userController/upload',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data',
      Authorization: sessionStorage.getItem('token') || localStorage.getItem('token')
    }
  })
}

/**
 * 生成验证码图片URL
 * @param {string} id - 验证码ID
 * @returns {string} - 返回验证码图片URL
 */
export const generateCaptchaUrl = (id) => {
  return `/captchaService/captcha/generate?id=${id}`
}

/**
 * 生成随机验证码ID
 * @returns {string} - 返回随机生成的验证码ID
 */
export const generateCaptchaId = () => {
  return Math.random().toString(36).substring(2)
}

/**
 * 验证验证码
 * @param {Object} data - 验证码数据
 * @param {string} data.captchaId - 验证码ID
 * @param {string} data.captcha - 用户输入的验证码
 * @returns {Promise} - 返回验证结果
 */
export const verifyCaptcha = (data) => {
  if (!data || !data.captchaId || !data.captcha) {
    return Promise.reject(new Error('验证码参数不完整'))
  }
  
  return request({
    url: '/captchaService/captcha/verify',
    method: 'post',
    data: {
      id: data.captchaId.toString(),
      code: data.captcha.toUpperCase()
    }
  })
}

/**
 * 发送重置手机号验证码
 * @param {string} mobile - 手机号码
 * @returns {Promise} - 返回发送结果
 */
export const sendResetMessageCode = (mobile) => {
  return request({
    url: '/userService/userController/sendResetMessageCode',
    method: 'get',
    params: { mobile }
  })
}

/**
 * 校验重置手机号验证码
 * @param {string} mobile - 手机号码
 * @param {string} userCode - 用户输入的验证码
 * @returns {Promise} - 返回验证结果
 */
export const checkResetMessageCode = (mobile, userCode) => {
  return request({
    url: '/userService/userController/checkResetMessageCode',
    method: 'get',
    params: { 
      mobile,
      userCode
    }
  })
}

/**
 * 验证token与用户ID是否匹配
 * @param {number} userId - 用户ID
 * @returns {Promise} - 返回验证结果
 */
export function verifyToken(userId) {
  if (!userId) {
    // 静默返回失败而不是抛出错误
    return Promise.resolve({ code: 0, data: false });
  }
  
  return request({
    url: '/userService/userController/verifyToken',
    method: 'get',
    params: { 
      userId
    },
    headers: {
      Authorization: sessionStorage.getItem('token') || localStorage.getItem('token')
    }
  }).catch(error => {
    // 捕获错误但不向上抛出，而是返回一个静默失败的结果
    console.error('验证用户身份失败:', error);
    return { code: 0, data: false };
  });
}

/**
 * 获取未读通知数量
 * @returns {Promise<Object>} 包含未读通知数量的响应对象
 */
export function getUnreadNotification() {
  return request({
    url: '/notificationService/notificationController/getUnreadNotification',
    method: 'get',
    headers: {
      'Content-Type': 'multipart/form-data',
      Authorization: sessionStorage.getItem('token') || localStorage.getItem('token')
    }
  })
}

/**
 * 获取用户通知列表
 * @returns {Promise<Object>} 包含通知列表的响应对象
 */
export function getNotificationList() {
  return request({
    url: '/notificationService/notificationController/getNotificationList',
    method: 'get',
    headers: {
      Authorization: sessionStorage.getItem('token') || localStorage.getItem('token')
    }
  })
}

/**
 * 标记通知为已读
 * @param {number} notificationId - 通知ID
 * @returns {Promise<Object>} 响应对象
 */
export function readNotification(notificationId) {
  return request({
    url: '/notificationService/notificationController/readNotification',
    method: 'get',
    params: {
      notificationId
    },
    headers: {
      Authorization: sessionStorage.getItem('token') || localStorage.getItem('token')
    }
  })
}

/**
 * 删除通知
 * @param {number} notificationId - 通知ID
 * @returns {Promise<Object>} 响应对象
 */
export function deleteNotification(notificationId) {
  return request({
    url: '/notificationService/notificationController/deleteNotification',
    method: 'delete',
    params: {
      notificationId
    },
    headers: {
      Authorization: sessionStorage.getItem('token') || localStorage.getItem('token')
    }
  })
}

/**
 * 根据用户名获取用户头像
 * @param {string} userName - 用户名
 * @returns {Promise<string>} - 返回头像URL
 */
export const getUserAvatarByName = async (userName) => {
  try {
    const response = await axios.get('/userService/userController/getUserAvatarByName', {
      params: { userName }
    })
    return response.data.code === 200 ? response.data.data : ''
  } catch (error) {
    console.error('获取用户头像失败:', error)
    return ''
  }
}